<!DOCTYPE html><html lang="zh-CN" data-theme="light"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no"><title>自制深度学习框架--实现表达式层ExpressionLayer | kiloGrand</title><meta name="keywords" content="kuiper_infer"><meta name="author" content="kiloGrand"><meta name="copyright" content="kiloGrand"><meta name="format-detection" content="telephone=no"><meta name="theme-color" content="#ffffff"><meta name="description" content="Expression Operator Operator是用来存储计算图信息的，即负责某类型节点参数的记录。 在这里我们定义了一个表达式算子ExpressionOp，通过ExpressionParser类来解析expr表达式字符串，同时定义了一个方法，把逆波兰表达式保存到nodes中。12345678910class ExpressionOp : public Operator &amp;#123; pu">
<meta property="og:type" content="article">
<meta property="og:title" content="自制深度学习框架--实现表达式层ExpressionLayer">
<meta property="og:url" content="https://kilogrand.gitee.io/2023/03/19/kuiper_infer-L9/index.html">
<meta property="og:site_name" content="kiloGrand">
<meta property="og:description" content="Expression Operator Operator是用来存储计算图信息的，即负责某类型节点参数的记录。 在这里我们定义了一个表达式算子ExpressionOp，通过ExpressionParser类来解析expr表达式字符串，同时定义了一个方法，把逆波兰表达式保存到nodes中。12345678910class ExpressionOp : public Operator &amp;#123; pu">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://kilogrand.gitee.io/img/coding.jpg">
<meta property="article:published_time" content="2023-03-19T12:00:00.000Z">
<meta property="article:modified_time" content="2023-04-18T14:41:55.691Z">
<meta property="article:author" content="kiloGrand">
<meta property="article:tag" content="kuiper_infer">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://kilogrand.gitee.io/img/coding.jpg"><link rel="shortcut icon" href="/img/favicon.png"><link rel="canonical" href="https://kilogrand.gitee.io/2023/03/19/kuiper_infer-L9/"><link rel="preconnect" href="//cdn.jsdelivr.net"/><link rel="preconnect" href="//busuanzi.ibruce.info"/><link rel="stylesheet" href="/css/index.css"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free@6/css/all.min.css" media="print" onload="this.media='all'"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fancyapps/ui/dist/fancybox.css" media="print" onload="this.media='all'"><script>const GLOBAL_CONFIG = { 
  root: '/',
  algolia: undefined,
  localSearch: {"path":"/search.xml","preload":false,"languages":{"hits_empty":"找不到您查询的内容：${query}"}},
  translate: undefined,
  noticeOutdate: undefined,
  highlight: {"plugin":"highlighjs","highlightCopy":true,"highlightLang":true,"highlightHeightLimit":false},
  copy: {
    success: '复制成功',
    error: '复制错误',
    noSupport: '浏览器不支持'
  },
  relativeDate: {
    homepage: false,
    post: false
  },
  runtime: '',
  date_suffix: {
    just: '刚刚',
    min: '分钟前',
    hour: '小时前',
    day: '天前',
    month: '个月前'
  },
  copyright: undefined,
  lightbox: 'fancybox',
  Snackbar: undefined,
  source: {
    justifiedGallery: {
      js: 'https://cdn.jsdelivr.net/npm/flickr-justified-gallery@2/dist/fjGallery.min.js',
      css: 'https://cdn.jsdelivr.net/npm/flickr-justified-gallery@2/dist/fjGallery.min.css'
    }
  },
  isPhotoFigcaption: false,
  islazyload: false,
  isAnchor: true
}</script><script id="config-diff">var GLOBAL_CONFIG_SITE = {
  title: '自制深度学习框架--实现表达式层ExpressionLayer',
  isPost: true,
  isHome: false,
  isHighlightShrink: false,
  isToc: true,
  postUpdate: '2023-04-18 22:41:55'
}</script><noscript><style type="text/css">
  #nav {
    opacity: 1
  }
  .justified-gallery img {
    opacity: 1
  }

  #recent-posts time,
  #post-meta time {
    display: inline !important
  }
</style></noscript><script>(win=>{
    win.saveToLocal = {
      set: function setWithExpiry(key, value, ttl) {
        if (ttl === 0) return
        const now = new Date()
        const expiryDay = ttl * 86400000
        const item = {
          value: value,
          expiry: now.getTime() + expiryDay,
        }
        localStorage.setItem(key, JSON.stringify(item))
      },

      get: function getWithExpiry(key) {
        const itemStr = localStorage.getItem(key)

        if (!itemStr) {
          return undefined
        }
        const item = JSON.parse(itemStr)
        const now = new Date()

        if (now.getTime() > item.expiry) {
          localStorage.removeItem(key)
          return undefined
        }
        return item.value
      }
    }
  
    win.getScript = url => new Promise((resolve, reject) => {
      const script = document.createElement('script')
      script.src = url
      script.async = true
      script.onerror = reject
      script.onload = script.onreadystatechange = function() {
        const loadState = this.readyState
        if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
        script.onload = script.onreadystatechange = null
        resolve()
      }
      document.head.appendChild(script)
    })
  
      win.activateDarkMode = function () {
        document.documentElement.setAttribute('data-theme', 'dark')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#0d0d0d')
        }
      }
      win.activateLightMode = function () {
        document.documentElement.setAttribute('data-theme', 'light')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#ffffff')
        }
      }
      const t = saveToLocal.get('theme')
    
          if (t === 'dark') activateDarkMode()
          else if (t === 'light') activateLightMode()
        
    const detectApple = () => {
      if(/iPad|iPhone|iPod|Macintosh/.test(navigator.userAgent)){
        document.documentElement.classList.add('apple')
      }
    }
    detectApple()
    })(window)</script><meta name="generator" content="Hexo 5.4.2"></head><body><div id="sidebar"><div id="menu-mask"></div><div id="sidebar-menus"><div class="avatar-img is-center"><img src="/img/profile.png" onerror="onerror=null;src='/img/friend_404.gif'" alt="avatar"/></div><div class="sidebar-site-data site-data is-center"><a href="/archives/"><div class="headline">文章</div><div class="length-num">46</div></a><a href="/tags/"><div class="headline">标签</div><div class="length-num">6</div></a><a href="/categories/"><div class="headline">分类</div><div class="length-num">5</div></a></div><hr/><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> 主页</span></a></div><div class="menus_item"><a class="site-page" href="/archives/"><i class="fa-fw fas fa-archive"></i><span> 归档</span></a></div><div class="menus_item"><a class="site-page" href="/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/categories/"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></div><div class="menus_item"><a class="site-page" href="/link/"><i class="fa-fw fas fa-link"></i><span> Link</span></a></div></div></div></div><div class="post" id="body-wrap"><header class="post-bg" id="page-header" style="background-image: url('/img/coding.jpg')"><nav id="nav"><span id="blog_name"><a id="site-name" href="/">kiloGrand</a></span><div id="menus"><div id="search-button"><a class="site-page social-icon search"><i class="fas fa-search fa-fw"></i><span> 搜索</span></a></div><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> 主页</span></a></div><div class="menus_item"><a class="site-page" href="/archives/"><i class="fa-fw fas fa-archive"></i><span> 归档</span></a></div><div class="menus_item"><a class="site-page" href="/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/categories/"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></div><div class="menus_item"><a class="site-page" href="/link/"><i class="fa-fw fas fa-link"></i><span> Link</span></a></div></div><div id="toggle-menu"><a class="site-page"><i class="fas fa-bars fa-fw"></i></a></div></div></nav><div id="post-info"><h1 class="post-title">自制深度学习框架--实现表达式层ExpressionLayer</h1><div id="post-meta"><div class="meta-firstline"><span class="post-meta-date"><i class="far fa-calendar-alt fa-fw post-meta-icon"></i><span class="post-meta-label">发表于</span><time class="post-meta-date-created" datetime="2023-03-19T12:00:00.000Z" title="发表于 2023-03-19 20:00:00">2023-03-19</time><span class="post-meta-separator">|</span><i class="fas fa-history fa-fw post-meta-icon"></i><span class="post-meta-label">更新于</span><time class="post-meta-date-updated" datetime="2023-04-18T14:41:55.691Z" title="更新于 2023-04-18 22:41:55">2023-04-18</time></span><span class="post-meta-categories"><span class="post-meta-separator">|</span><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/categories/%E6%B7%B1%E5%BA%A6%E5%AD%A6%E4%B9%A0/">深度学习</a></span></div><div class="meta-secondline"><span class="post-meta-separator">|</span><span class="post-meta-wordcount"><i class="far fa-file-word fa-fw post-meta-icon"></i><span class="post-meta-label">字数总计:</span><span class="word-count">1k</span><span class="post-meta-separator">|</span><i class="far fa-clock fa-fw post-meta-icon"></i><span class="post-meta-label">阅读时长:</span><span>5分钟</span></span><span class="post-meta-separator">|</span><span class="post-meta-pv-cv" id="" data-flag-title="自制深度学习框架--实现表达式层ExpressionLayer"><i class="far fa-eye fa-fw post-meta-icon"></i><span class="post-meta-label">阅读量:</span><span id="busuanzi_value_page_pv"></span></span></div></div></div></header><main class="layout" id="content-inner"><div id="post"><article class="post-content" id="article-container"><h2 id="Expression-Operator"><a href="#Expression-Operator" class="headerlink" title="Expression Operator"></a>Expression Operator</h2><ul>
<li>Operator是用来存储计算图信息的，即负责某类型节点参数的记录。</li>
<li>在这里我们定义了一个表达式算子ExpressionOp，通过ExpressionParser类来解析expr<em>表达式字符串，<br>同时定义了一个方法，把逆波兰表达式保存到nodes</em>中。<figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">ExpressionOp</span> : <span class="keyword">public</span> Operator &#123;</span><br><span class="line"> <span class="keyword">public</span>:</span><br><span class="line">  <span class="function"><span class="keyword">explicit</span> <span class="title">ExpressionOp</span><span class="params">(<span class="type">const</span> std::string &amp;expr)</span></span>;</span><br><span class="line">  std::vector&lt;std::shared_ptr&lt;TokenNode&gt;&gt; <span class="built_in">Generate</span>();  <span class="comment">// 生成逆波兰表达式</span></span><br><span class="line"></span><br><span class="line"> <span class="keyword">private</span>:</span><br><span class="line">  std::unique_ptr&lt;ExpressionParser&gt; parser_;  <span class="comment">// 指向ExpressionParser类的指针，用于语法分析和词法分析</span></span><br><span class="line">  std::vector&lt;std::shared_ptr&lt;TokenNode&gt;&gt; nodes_;  <span class="comment">// 逆波兰之后的表达式，也是一个list</span></span><br><span class="line">  std::string expr_;  <span class="comment">// 表达式字符串</span></span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>
</li>
</ul>
<figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 初始化ExpressionOp</span></span><br><span class="line">ExpressionOp::<span class="built_in">ExpressionOp</span>(<span class="type">const</span> std::string &amp;expr) : <span class="built_in">Operator</span>(OpType::kOperatorExpression), <span class="built_in">expr_</span>(expr) &#123;</span><br><span class="line">  <span class="comment">// 实例化ExpressionParser</span></span><br><span class="line">  <span class="keyword">this</span>-&gt;parser_ = std::<span class="built_in">make_shared</span>&lt;ExpressionParser&gt;(<span class="keyword">this</span>-&gt;expr_);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 词法和语法解析，并返回逆波兰表达式</span></span><br><span class="line">std::vector&lt;std::shared_ptr&lt;TokenNode&gt;&gt; ExpressionOp::<span class="built_in">Generate</span>() &#123;</span><br><span class="line">  <span class="built_in">CHECK</span>(<span class="keyword">this</span>-&gt;parser_ != <span class="literal">nullptr</span>);</span><br><span class="line">  <span class="keyword">this</span>-&gt;nodes_ = <span class="keyword">this</span>-&gt;parser_-&gt;<span class="built_in">Generate</span>();</span><br><span class="line">  <span class="keyword">return</span> <span class="keyword">this</span>-&gt;nodes_;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h2 id="ExpressionLayer的定义"><a href="#ExpressionLayer的定义" class="headerlink" title="ExpressionLayer的定义"></a>ExpressionLayer的定义</h2><ul>
<li>layer负责对应节点的具体计算</li>
<li>在这里我们定义了ExpressionLayer，实现它的前向传播<figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">ExpressionLayer</span> : <span class="keyword">public</span> Layer &#123;</span><br><span class="line"> <span class="keyword">public</span>:</span><br><span class="line">  <span class="function"><span class="keyword">explicit</span> <span class="title">ExpressionLayer</span><span class="params">(<span class="type">const</span> std::shared_ptr&lt;Operator&gt; &amp;op)</span></span>;</span><br><span class="line">  <span class="comment">// 前向传播</span></span><br><span class="line">  <span class="function"><span class="type">void</span> <span class="title">Forwards</span><span class="params">(<span class="type">const</span> std::vector&lt;std::shared_ptr&lt;Tensor&lt;<span class="type">float</span>&gt;&gt;&gt; &amp;inputs,</span></span></span><br><span class="line"><span class="params"><span class="function">                std::vector&lt;std::shared_ptr&lt;Tensor&lt;<span class="type">float</span>&gt;&gt;&gt; &amp;outputs)</span> <span class="keyword">override</span></span>;</span><br><span class="line"> <span class="keyword">private</span>:</span><br><span class="line">  std::unique_ptr&lt;ExpressionOp&gt; op_;</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>
</li>
</ul>
<h2 id="初始化Expression-Layer"><a href="#初始化Expression-Layer" class="headerlink" title="初始化Expression Layer"></a>初始化Expression Layer</h2><figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">ExpressionLayer::<span class="built_in">ExpressionLayer</span>(<span class="type">const</span> std::shared_ptr&lt;Operator&gt; &amp;op) : <span class="built_in">Layer</span>(<span class="string">&quot;Expression&quot;</span>) &#123;</span><br><span class="line">  <span class="comment">// OpType::kOperatorExpression = 3</span></span><br><span class="line">  <span class="built_in">CHECK</span>(op != <span class="literal">nullptr</span> &amp;&amp; op-&gt;op_type_ == OpType::kOperatorExpression);</span><br><span class="line">  <span class="comment">// 智能指针 通过op.get()得到普通指针 通过dynamic_cast 转换为ExpressionOp *</span></span><br><span class="line">  ExpressionOp *expression_op = <span class="built_in">dynamic_cast</span>&lt;ExpressionOp *&gt;(op.<span class="built_in">get</span>());</span><br><span class="line"></span><br><span class="line">  <span class="built_in">CHECK</span>(expression_op != <span class="literal">nullptr</span>) &lt;&lt; <span class="string">&quot;Expression operator is empty&quot;</span>;</span><br><span class="line">  <span class="keyword">this</span>-&gt;op_ = std::<span class="built_in">make_unique</span>&lt;ExpressionOp&gt;(*expression_op);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h2 id="前向传播的实现"><a href="#前向传播的实现" class="headerlink" title="前向传播的实现"></a>前向传播的实现</h2><ol>
<li>初始化outputs数组中的元素全部为0</li>
<li>初始化栈，在逆波兰表达式的计算中，存储临时张量</li>
<li>生成逆波兰表达式</li>
<li>遍历逆波兰表达式<ul>
<li>如果是操作数，读取一个批次的数据，把数据临时存放到栈中</li>
<li>如果是操作符，获取栈顶的操作数，并出栈，计算，计算结果进栈<figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="type">void</span> <span class="title">ExpressionLayer::Forwards</span><span class="params">(<span class="type">const</span> std::vector&lt;std::shared_ptr&lt;Tensor&lt;<span class="type">float</span>&gt;&gt;&gt; &amp;inputs,</span></span></span><br><span class="line"><span class="params"><span class="function">                               std::vector&lt;std::shared_ptr&lt;Tensor&lt;<span class="type">float</span>&gt;&gt;&gt; &amp;outputs)</span> </span>&#123;</span><br><span class="line">  <span class="built_in">CHECK</span>(!inputs.<span class="built_in">empty</span>());</span><br><span class="line"></span><br><span class="line">  <span class="type">const</span> <span class="type">uint32_t</span> batch_size = outputs.<span class="built_in">size</span>();</span><br><span class="line">  <span class="built_in">CHECK</span>(batch_size != <span class="number">0</span>);</span><br><span class="line">  <span class="comment">// 初始化outputs数组中的元素全部为0</span></span><br><span class="line">  <span class="keyword">for</span> (<span class="type">uint32_t</span> i = <span class="number">0</span>; i &lt; batch_size; ++i) &#123;</span><br><span class="line">    <span class="built_in">CHECK</span>(outputs.<span class="built_in">at</span>(i) != <span class="literal">nullptr</span> &amp;&amp; !outputs.<span class="built_in">at</span>(i)-&gt;<span class="built_in">empty</span>());</span><br><span class="line">    outputs.<span class="built_in">at</span>(i)-&gt;<span class="built_in">Fill</span>(<span class="number">0.f</span>);</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  <span class="built_in">CHECK</span>(<span class="keyword">this</span>-&gt;op_ != <span class="literal">nullptr</span> &amp;&amp; <span class="keyword">this</span>-&gt;op_-&gt;op_type_ == OpType::kOperatorExpression);</span><br><span class="line">  <span class="comment">// 初始化栈，在逆波兰表达式的计算中，存储临时张量</span></span><br><span class="line">  std::stack&lt;std::vector&lt;std::shared_ptr&lt;Tensor&lt;<span class="type">float</span>&gt;&gt;&gt;&gt; op_stack;</span><br><span class="line">  <span class="comment">// 生成逆波兰表达式</span></span><br><span class="line">  <span class="type">const</span> std::vector&lt;std::shared_ptr&lt;TokenNode&gt;&gt; &amp;token_nodes = <span class="keyword">this</span>-&gt;op_-&gt;<span class="built_in">Generate</span>();</span><br><span class="line"></span><br><span class="line">  <span class="comment">// 遍历逆波兰表达式</span></span><br><span class="line">  <span class="keyword">for</span> (<span class="type">const</span> <span class="keyword">auto</span> &amp;token_node : token_nodes) &#123;</span><br><span class="line">    <span class="keyword">if</span> (token_node-&gt;num_index &gt;= <span class="number">0</span>) &#123;</span><br><span class="line">      <span class="comment">// 如果是操作数，例如@0，@1</span></span><br><span class="line">      <span class="type">uint32_t</span> start_pos = token_node-&gt;num_index * batch_size;</span><br><span class="line">      <span class="comment">// 读取一个批次的数据</span></span><br><span class="line">      std::vector&lt;std::shared_ptr&lt;Tensor&lt;<span class="type">float</span>&gt;&gt;&gt; input_token_nodes;</span><br><span class="line">      <span class="keyword">for</span> (<span class="type">uint32_t</span> i = <span class="number">0</span>; i &lt; batch_size; ++i) &#123;</span><br><span class="line">        <span class="built_in">CHECK</span>(i + start_pos &lt; inputs.<span class="built_in">size</span>());</span><br><span class="line">        input_token_nodes.<span class="built_in">push_back</span>(inputs.<span class="built_in">at</span>(i + start_pos));</span><br><span class="line">      &#125;</span><br><span class="line">      <span class="comment">// 把数据临时存放到栈中</span></span><br><span class="line">      op_stack.<span class="built_in">push</span>(input_token_nodes);</span><br><span class="line"></span><br><span class="line">    &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">      <span class="comment">// 如果是操作符，例如add，mul</span></span><br><span class="line">      <span class="type">const</span> <span class="type">int32_t</span> op = token_node-&gt;num_index;</span><br><span class="line">      <span class="built_in">CHECK</span>(op_stack.<span class="built_in">size</span>() &gt;= <span class="number">2</span>) &lt;&lt; <span class="string">&quot;The number of operand is less than two&quot;</span>;</span><br><span class="line">      <span class="comment">// 获取栈顶的操作数，并出栈</span></span><br><span class="line">      std::vector&lt;std::shared_ptr&lt;Tensor&lt;<span class="type">float</span>&gt;&gt;&gt; input_node1 = op_stack.<span class="built_in">top</span>();</span><br><span class="line">      <span class="built_in">CHECK</span>(input_node1.<span class="built_in">size</span>() == batch_size);</span><br><span class="line">      op_stack.<span class="built_in">pop</span>();</span><br><span class="line">      <span class="comment">// 获取栈顶的操作数，并出栈</span></span><br><span class="line">      std::vector&lt;std::shared_ptr&lt;Tensor&lt;<span class="type">float</span>&gt;&gt;&gt; input_node2 = op_stack.<span class="built_in">top</span>();</span><br><span class="line">      <span class="built_in">CHECK</span>(input_node2.<span class="built_in">size</span>() == batch_size);</span><br><span class="line">      op_stack.<span class="built_in">pop</span>();</span><br><span class="line">      <span class="comment">// 计算</span></span><br><span class="line">      <span class="built_in">CHECK</span>(input_node1.<span class="built_in">size</span>() == input_node2.<span class="built_in">size</span>());</span><br><span class="line">      std::vector&lt;std::shared_ptr&lt;Tensor&lt;<span class="type">float</span>&gt;&gt;&gt; <span class="built_in">output_token_nodes</span>(batch_size);</span><br><span class="line">      <span class="keyword">for</span> (<span class="type">uint32_t</span> i = <span class="number">0</span>; i &lt; batch_size; ++i) &#123;</span><br><span class="line">        <span class="keyword">if</span> (op == -<span class="built_in">int</span>(TokenType::TokenAdd)) &#123;</span><br><span class="line">          <span class="comment">// element-wise add</span></span><br><span class="line">          output_token_nodes.<span class="built_in">at</span>(i) = ftensor::<span class="built_in">ElementAdd</span>(input_node1.<span class="built_in">at</span>(i), input_node2.<span class="built_in">at</span>(i));</span><br><span class="line">        &#125; <span class="keyword">else</span> <span class="keyword">if</span> (op == -<span class="built_in">int</span>(TokenType::TokenMul)) &#123;</span><br><span class="line">          <span class="comment">// element-wise mul</span></span><br><span class="line">          output_token_nodes.<span class="built_in">at</span>(i) = ftensor::<span class="built_in">ElementMultiply</span>(input_node1.<span class="built_in">at</span>(i), input_node2.<span class="built_in">at</span>(i));</span><br><span class="line">        &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">          <span class="built_in">LOG</span>(FATAL) &lt;&lt; <span class="string">&quot;Unknown operator type: &quot;</span> &lt;&lt; op;</span><br><span class="line">        &#125;</span><br><span class="line">      &#125;</span><br><span class="line">      <span class="comment">// 计算结果进栈</span></span><br><span class="line">      op_stack.<span class="built_in">push</span>(output_token_nodes);</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  <span class="comment">// 获取最终计算结果，并出栈</span></span><br><span class="line">  <span class="built_in">CHECK</span>(op_stack.<span class="built_in">size</span>() == <span class="number">1</span>);</span><br><span class="line">  std::vector&lt;std::shared_ptr&lt;Tensor&lt;<span class="type">float</span>&gt;&gt;&gt; output_node = op_stack.<span class="built_in">top</span>();</span><br><span class="line">  op_stack.<span class="built_in">pop</span>();</span><br><span class="line"></span><br><span class="line">  <span class="keyword">for</span> (<span class="type">int</span> i = <span class="number">0</span>; i &lt; batch_size; ++i) &#123;</span><br><span class="line">    <span class="built_in">CHECK</span>(outputs.<span class="built_in">at</span>(i) != <span class="literal">nullptr</span> &amp;&amp; !outputs.<span class="built_in">at</span>(i)-&gt;<span class="built_in">empty</span>());</span><br><span class="line">    outputs.<span class="built_in">at</span>(i) = output_node.<span class="built_in">at</span>(i);</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
</li>
</ul>
</li>
</ol>
</article><div class="post-copyright"><div class="post-copyright__author"><span class="post-copyright-meta">文章作者: </span><span class="post-copyright-info"><a href="https://kilogrand.gitee.io">kiloGrand</a></span></div><div class="post-copyright__type"><span class="post-copyright-meta">文章链接: </span><span class="post-copyright-info"><a href="https://kilogrand.gitee.io/2023/03/19/kuiper_infer-L9/">https://kilogrand.gitee.io/2023/03/19/kuiper_infer-L9/</a></span></div><div class="post-copyright__notice"><span class="post-copyright-meta">版权声明: </span><span class="post-copyright-info">本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" target="_blank">CC BY-NC-SA 4.0</a> 许可协议。转载请注明来自 <a href="https://kilogrand.gitee.io" target="_blank">kiloGrand</a>！</span></div></div><div class="tag_share"><div class="post-meta__tag-list"><a class="post-meta__tags" href="/tags/kuiper-infer/">kuiper_infer</a></div><div class="post_share"></div></div><nav class="pagination-post" id="pagination"><div class="prev-post pull-left"><a href="/2023/03/18/kuiper_infer-L8/"><img class="prev-cover" src="/img/coding.jpg" onerror="onerror=null;src='/img/404.jpg'" alt="cover of previous post"><div class="pagination-info"><div class="label">上一篇</div><div class="prev_info">自制深度学习框架--计算图中表达式的解析</div></div></a></div><div class="next-post pull-right"><a href="/2023/03/20/kuiper_infer-L10/"><img class="next-cover" src="/img/coding.jpg" onerror="onerror=null;src='/img/404.jpg'" alt="cover of next post"><div class="pagination-info"><div class="label">下一篇</div><div class="next_info">自制深度学习框架--Im2Col原理与卷积层的实现</div></div></a></div></nav><div class="relatedPosts"><div class="headline"><i class="fas fa-thumbs-up fa-fw"></i><span>相关推荐</span></div><div class="relatedPosts-list"><div><a href="/2023/03/20/kuiper_infer-L10/" title="自制深度学习框架--Im2Col原理与卷积层的实现"><img class="cover" src="/img/coding.jpg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2023-03-20</div><div class="title">自制深度学习框架--Im2Col原理与卷积层的实现</div></div></a></div><div><a href="/2023/03/21/kuiper_infer-L11/" title="自制深度学习框架--再探Tensor类并构建计算图的图关系"><img class="cover" src="/img/coding.jpg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2023-03-21</div><div class="title">自制深度学习框架--再探Tensor类并构建计算图的图关系</div></div></a></div><div><a href="/2023/03/24/kuiper_infer-L14/" title="自制深度学习框架--实现Yolov5的推理"><img class="cover" src="/img/coding.jpg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2023-03-24</div><div class="title">自制深度学习框架--实现Yolov5的推理</div></div></a></div><div><a href="/2023/03/22/kuiper_infer-L12/" title="自制深度学习框架--算子的执行流程"><img class="cover" src="/img/coding.jpg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2023-03-22</div><div class="title">自制深度学习框架--算子的执行流程</div></div></a></div><div><a href="/2023/03/23/kuiper_infer-L13/" title="自制深度学习框架--实现ResNet网络的推理"><img class="cover" src="/img/coding.jpg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2023-03-23</div><div class="title">自制深度学习框架--实现ResNet网络的推理</div></div></a></div><div><a href="/2023/03/14/kuiper_infer-L3/" title="自制深度学习框架--导入数据"><img class="cover" src="/img/coding.jpg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2023-03-14</div><div class="title">自制深度学习框架--导入数据</div></div></a></div></div></div></div><div class="aside-content" id="aside-content"><div class="card-widget card-info"><div class="is-center"><div class="avatar-img"><img src="/img/profile.png" onerror="this.onerror=null;this.src='/img/friend_404.gif'" alt="avatar"/></div><div class="author-info__name">kiloGrand</div><div class="author-info__description">coder && data-science researcher</div></div><div class="card-info-data site-data is-center"><a href="/archives/"><div class="headline">文章</div><div class="length-num">46</div></a><a href="/tags/"><div class="headline">标签</div><div class="length-num">6</div></a><a href="/categories/"><div class="headline">分类</div><div class="length-num">5</div></a></div><a id="card-info-btn" target="_blank" rel="noopener" href="https://github.com/kiloGrand/"><i class="fab fa-github"></i><span>Follow Me</span></a></div><div class="card-widget card-announcement"><div class="item-headline"><i class="fas fa-bullhorn fa-shake"></i><span>公告</span></div><div class="announcement_content">This is my Blog</div></div><div class="sticky_layout"><div class="card-widget" id="card-toc"><div class="item-headline"><i class="fas fa-stream"></i><span>目录</span><span class="toc-percentage"></span></div><div class="toc-content"><ol class="toc"><li class="toc-item toc-level-2"><a class="toc-link" href="#Expression-Operator"><span class="toc-number">1.</span> <span class="toc-text">Expression Operator</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#ExpressionLayer%E7%9A%84%E5%AE%9A%E4%B9%89"><span class="toc-number">2.</span> <span class="toc-text">ExpressionLayer的定义</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%88%9D%E5%A7%8B%E5%8C%96Expression-Layer"><span class="toc-number">3.</span> <span class="toc-text">初始化Expression Layer</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%89%8D%E5%90%91%E4%BC%A0%E6%92%AD%E7%9A%84%E5%AE%9E%E7%8E%B0"><span class="toc-number">4.</span> <span class="toc-text">前向传播的实现</span></a></li></ol></div></div><div class="card-widget card-recent-post"><div class="item-headline"><i class="fas fa-history"></i><span>最新文章</span></div><div class="aside-list"><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/2023/03/24/kuiper_infer-L14/" title="自制深度学习框架--实现Yolov5的推理">自制深度学习框架--实现Yolov5的推理</a><time datetime="2023-03-24T12:00:00.000Z" title="发表于 2023-03-24 20:00:00">2023-03-24</time></div></div><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/2023/03/23/kuiper_infer-L13/" title="自制深度学习框架--实现ResNet网络的推理">自制深度学习框架--实现ResNet网络的推理</a><time datetime="2023-03-23T12:00:00.000Z" title="发表于 2023-03-23 20:00:00">2023-03-23</time></div></div><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/2023/03/22/kuiper_infer-L12/" title="自制深度学习框架--算子的执行流程">自制深度学习框架--算子的执行流程</a><time datetime="2023-03-22T12:00:00.000Z" title="发表于 2023-03-22 20:00:00">2023-03-22</time></div></div><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/2023/03/21/kuiper_infer-L11/" title="自制深度学习框架--再探Tensor类并构建计算图的图关系">自制深度学习框架--再探Tensor类并构建计算图的图关系</a><time datetime="2023-03-21T12:00:00.000Z" title="发表于 2023-03-21 20:00:00">2023-03-21</time></div></div><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/2023/03/20/kuiper_infer-L10/" title="自制深度学习框架--Im2Col原理与卷积层的实现">自制深度学习框架--Im2Col原理与卷积层的实现</a><time datetime="2023-03-20T12:00:00.000Z" title="发表于 2023-03-20 20:00:00">2023-03-20</time></div></div></div></div></div></div></main><footer id="footer"><div id="footer-wrap"><div class="copyright">&copy;2022 - 2023 By kiloGrand</div><div class="footer_custom_text">Hi, welcome to my blog!</div></div></footer></div><div id="rightside"><div id="rightside-config-hide"><button id="readmode" type="button" title="阅读模式"><i class="fas fa-book-open"></i></button><button id="darkmode" type="button" title="浅色和深色模式转换"><i class="fas fa-adjust"></i></button></div><div id="rightside-config-show"><button id="rightside_config" type="button" title="设置"><i class="fas fa-cog fa-spin"></i></button><button class="close" id="mobile-toc-button" type="button" title="目录"><i class="fas fa-list-ul"></i></button><button id="go-up" type="button" title="回到顶部"><i class="fas fa-arrow-up"></i></button></div></div><div id="local-search"><div class="search-dialog"><nav class="search-nav"><span class="search-dialog-title">搜索</span><span id="loading-status"></span><button class="search-close-button"><i class="fas fa-times"></i></button></nav><div class="is-center" id="loading-database"><i class="fas fa-spinner fa-pulse"></i><span>  数据库加载中</span></div><div class="search-wrap"><div id="local-search-input"><div class="local-search-box"><input class="local-search-box--input" placeholder="搜索文章" type="text"/></div></div><hr/><div id="local-search-results"></div></div></div><div id="search-mask"></div></div><div><script src="/js/utils.js"></script><script src="/js/main.js"></script><script src="https://cdn.jsdelivr.net/npm/@fancyapps/ui/dist/fancybox.umd.js"></script><script src="/js/search/local-search.js"></script><div class="js-pjax"><script>if (!window.MathJax) {
  window.MathJax = {
    tex: {
      inlineMath: [ ['$','$'], ["\\(","\\)"]],
      tags: 'ams'
    },
    chtml: {
      scale: 1.2
    },
    options: {
      renderActions: {
        findScript: [10, doc => {
          for (const node of document.querySelectorAll('script[type^="math/tex"]')) {
            const display = !!node.type.match(/; *mode=display/)
            const math = new doc.options.MathItem(node.textContent, doc.inputJax[0], display)
            const text = document.createTextNode('')
            node.parentNode.replaceChild(text, node)
            math.start = {node: text, delim: '', n: 0}
            math.end = {node: text, delim: '', n: 0}
            doc.math.push(math)
          }
        }, ''],
        insertScript: [200, () => {
          document.querySelectorAll('mjx-container:not\([display]\)').forEach(node => {
            const target = node.parentNode
            if (target.nodeName.toLowerCase() === 'li') {
              target.parentNode.classList.add('has-jax')
            } else {
              target.classList.add('has-jax')
            }
          });
        }, '', false]
      }
    }
  }
  
  const script = document.createElement('script')
  script.src = 'https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-mml-chtml.js'
  script.id = 'MathJax-script'
  script.async = true
  document.head.appendChild(script)
} else {
  MathJax.startup.document.state(0)
  MathJax.texReset()
  MathJax.typeset()
}</script></div><script async data-pjax src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script></div></body></html>